博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Struts学习之 实现文件上传、下载操作
阅读量:5245 次
发布时间:2019-06-14

本文共 9191 字,大约阅读时间需要 30 分钟。

一、Struts-cofig.xml流程图

二、register.jsp页面文件

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>      My JSP 'register.jsp' starting page          

注册用户

Name:
Photo:
注册页面

三、RegisterAction文件

/* * Generated by MyEclipse Struts * Template path: templates/java/JavaClass.vtl */package com.zkj.struts.action;import java.io.FileOutputStream;import java.io.InputStream;import java.io.OutputStream;import java.util.UUID;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import org.apache.struts.action.Action;import org.apache.struts.action.ActionForm;import org.apache.struts.action.ActionForward;import org.apache.struts.action.ActionMapping;import org.apache.struts.upload.FormFile;import com.zkj.entity.Users;import com.zkj.service.UsersService;import com.zkj.struts.form.UserForm;import com.zkj.utils.UpdownUtils;/** * MyEclipse Struts Creation date: 04-25-2015 *  * XDoclet definition: *  * @struts.action path="/register" name="userForm" scope="request" */public class RegisterAction extends Action {    /*     * Generated Methods     */    /**     * Method execute     *      * @param mapping     * @param form     * @param request     * @param response     * @return ActionForward     */    public ActionForward execute(ActionMapping mapping, ActionForm form,            HttpServletRequest request, HttpServletResponse response) {        UserForm userForm = (UserForm) form;// TODO Auto-generated method stub        // 取出表單數據        String name = userForm.getName();        FormFile ff = userForm.getPhoto();        // 通過formfile我們可以獲取關於用戶上傳文件的各種信息        String sFileName = ff.getFileName();        String sFileNameNew = UpdownUtils.getUuidFileName(sFileName);        int fsize = ff.getFileSize();        InputStream is = null;        OutputStream os = null;        try {            // 取得輸入流            is = ff.getInputStream();            // 得到输出流并保存到tomcat服务器的绝对路径            String sPath = request.getSession().getServletContext()                    .getRealPath("/file");            os = new FileOutputStream(sPath + "\\" + sFileNameNew);            int len = 0;            byte[] buff = new byte[1024];            // 循环处理            while ((len = is.read(buff)) > 0) {                // 读入一段,写入一段                os.write(buff, 0, len);            }            UsersService service = new UsersService();            try {                Users user = new Users();                user.setUsername(name);                user.setPhoto(sFileName);                user.setPhotouuid(sFileNameNew);                service.saveUser(user);            } finally {                service = null;            }        } catch (Exception e) {            e.printStackTrace();        } finally {            if (is != null)                try {                    is.close();                } catch (Exception e) {                }            if (os != null)                try {                    os.close();                } catch (Exception e) {                }        }        return mapping.findForward("ok");    }}
上传Action

四、list.jsp页面文件

1 <%@ page language="java" import="java.util.*" pageEncoding="utf-8"%> 2 <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> 3  4  5    6     7     My JSP 'list.jsp' starting page 8    9   10   11     
12

用户列表

13
18
14
15
16
17
19
20
21
22
23 24
主键 姓名 照片 操作
${user.userid } ${user.username } 下载图片文件
25
26 27
用户列表(带图片)

五、ListAction.java文件

public ActionForward execute(ActionMapping mapping, ActionForm form,            HttpServletRequest request, HttpServletResponse response) {        // TODO Auto-generated method stub        UsersService us = new UsersService();        try {            response.setCharacterEncoding("utf-8");            request.setAttribute("arr", us.getAllUsers());            return mapping.findForward("list");        } catch (Exception e) {            e.printStackTrace();        } finally {            us = null;        }        return null;    }
View Code

六、DownloadFileAction.java

/* * Generated by MyEclipse Struts * Template path: templates/java/JavaClass.vtl */package com.zkj.struts.action;import java.io.*;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import org.apache.struts.action.Action;import org.apache.struts.action.ActionForm;import org.apache.struts.action.ActionForward;import org.apache.struts.action.ActionMapping;import com.zkj.entity.Users;import com.zkj.service.UsersService;/** * MyEclipse Struts Creation date: 04-26-2015 *  * XDoclet definition: *  * @struts.action */public class DownloadFileAction extends Action {    /*     * Generated Methods     */    /**     * Method execute     *      * @param mapping     * @param form     * @param request     * @param response     * @return ActionForward     */    public ActionForward execute(ActionMapping mapping, ActionForm form,            HttpServletRequest request, HttpServletResponse response) {        // TODO Auto-generated method stub        // 下句,控制可以显示中文        response.setContentType("text/html;charset=utf-8");        int nId = Integer.parseInt(request.getParameter("id"));        InputStream is = null;        OutputStream os = null;        UsersService us = new UsersService();        try {            Users user = us.getUserById(nId);            // 得到输出流并保存到tomcat服务器的绝对路径            String sPath = request.getSession().getServletContext()                    .getRealPath("/file");            String sFileName = sPath + "\\" + user.getPhotouuid();            String sTrueName = user.getPhoto();            //如果源文件名中文,需要进行url编码            sTrueName = java.net.URLEncoder.encode(sTrueName, "utf-8");            //告诉浏览器,有一个文件需要下载            response.setHeader("Content-Disposition", "attachment; filename="                    + sTrueName);            // 取得輸入流            is = new FileInputStream(sFileName);            os = response.getOutputStream();            int len = 0;            byte[] buff = new byte[1024];            // 循环处理            while ((len = is.read(buff)) > 0) {                // 读入一段,写入一段                os.write(buff, 0, len);            }            return mapping.findForward("lst");        } catch (Exception e) {            e.printStackTrace();        } finally {            if (is != null)                try {                    is.close();                } catch (Exception e) {                }            if (os != null)                try {                    os.close();                } catch (Exception e) {                }            us = null;        }        return null;    }}
View Code

七、关键的UsersService业务处理类基于hibernate实现代码

package com.zkj.service;import java.util.ArrayList;import java.util.Iterator;import java.util.List;import org.hibernate.*;import com.zkj.entity.Users;import com.zkj.sessionfactory.HibernateSessionFactory;public class UsersService {    public static SessionFactory sf;    static {        try {            // 创建sessionfactory实例            sf = HibernateSessionFactory.getSessionFactory();        } catch (Exception e) {            e.printStackTrace();        }    }    public boolean saveUser(Users user) {        boolean result = false;        Session session = sf.openSession();        Transaction trans = null;        try {            trans = session.beginTransaction();            session.save(user);            trans.commit();        } catch (Exception e) {            if (trans != null) {                trans.rollback();            }            e.printStackTrace();        } finally {            session.close();        }        return result;    }    public ArrayList
getAllUsers() { ArrayList
result = new ArrayList
(); Session session = sf.openSession(); try { List list = session.createQuery("from com.zkj.entity.Users u") .list(); Iterator it = list.iterator(); while (it.hasNext()) { Users user = (Users) it.next(); result.add(user); } } catch (Exception e) { e.printStackTrace(); } finally { session.close(); } return result; } public Users getUserById(int aId) { Users result = null; Session session = sf.openSession(); try { List lst = session.createQuery( "from com.zkj.entity.Users u where u.userid=" + aId).list(); Iterator it = lst.iterator(); if (it.hasNext()) { result = (Users) it.next(); } } catch (Exception e) { e.printStackTrace(); } finally { session.close(); } return result; }}
View Code

 

转载于:https://www.cnblogs.com/jiqiwoniu/p/4458380.html

你可能感兴趣的文章
Jenkins关闭、重启,Jenkins服务的启动、停止方法。
查看>>
CF E2 - Array and Segments (Hard version) (线段树)
查看>>
Linux SPI总线和设备驱动架构之四:SPI数据传输的队列化
查看>>
SIGPIPE并产生一个信号处理
查看>>
CentOS
查看>>
Linux pipe函数
查看>>
java equals 小记
查看>>
爬虫-通用代码框架
查看>>
2019春 软件工程实践 助教总结
查看>>
YUV 格式的视频呈现
查看>>
Android弹出框的学习
查看>>
现代程序设计 作业1
查看>>
在android开发中添加外挂字体
查看>>
Zerver是一个C#开发的Nginx+PHP+Mysql+memcached+redis绿色集成开发环境
查看>>
多线程实现资源共享的问题学习与总结
查看>>
Learning-Python【26】:反射及内置方法
查看>>
torch教程[1]用numpy实现三层全连接神经网络
查看>>
java实现哈弗曼树
查看>>
转:Web 测试的创作与调试技术
查看>>
python学习笔记3-列表
查看>>